package com.lw.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author LW
 * @2020/9/22 17:43
 */
//动态的创建对象，通过反射
public class Test08 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
        Class c1 = Class.forName("com.lw.reflection.User");
        //构建一个对象========调用了类的无参构造器
        User user = (User)c1.newInstance();//本质是调用了类的无参构造器
        System.out.println(user);

        System.out.println("=======================================");
        //通过构造器创建对象
        //调用有参
        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user2 = (User)constructor.newInstance("lw", 1, 18);
        System.out.println(user2);

        System.out.println("=======================================");

        //通过反射调用普通方法
        User user3 = (User)c1.newInstance();
        Method setName = c1.getDeclaredMethod("setName", String.class);
        //（对象，“方法的值”）
        setName.invoke(user3,"lw");//调用,激活方法
        System.out.println(user3.getName());

        System.out.println("=======================================");

        //通过反射操作属性
        User user4 = (User)c1.newInstance();
        Field name = c1.getDeclaredField("name");
        //没权限   进入
        //不能直接操作私有属性，我们需要关闭程序的安全监测，属性或方法的
        name.setAccessible(true);//设置无障碍,**************************
        name.set(user4,"lw2");
        System.out.println(user4.getName());//User with modifiers "private"

    }
}
